package com.qdaily.ui;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.webkit.WebView;

import com.qdaily.supportlibrary.QdailyCodeApp;
import com.qdaily.supportlibrary.Report.CrashHandler;
import com.qdaily.supportlibrary.cache.LoadingImageCache;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.controller.ActivityController;
import com.qdaily.ui.data.DataBase.DBHelper;
import com.qdaily.ui.data.QDConfigManager;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache.QDArticleWebViewFileCacheMgr;
import com.qdaily.ui.util.QDTestServerSetHelper;

/**
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/2/15
 * Time: 23:47
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class QDApplication extends Application {

    private boolean isInit = false;

    public static boolean isDebugMode = false;

    private static QDApplication instance;
    public static QDApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        QLog.w("QDApplication", "init");
        if (isInit)
        {
            return;
        }
        isInit = true;

        instance = this;
        if (BuildConfig.DEBUG)
        {
            isDebugMode = true;
        }
        else
        {
            try {
                ApplicationInfo appInfo = getApplicationContext().getPackageManager().getApplicationInfo(getApplicationContext().getPackageName(),
                        PackageManager.GET_META_DATA);
                String dataName=appInfo.metaData.getString("BaiduMobAd_CHANNEL");
                if (dataName.equals("开发版") || dataName.equals("debug"))
                {
                    isDebugMode = true;
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        QLog.isDebug = isDebugMode;

        DBHelper.init(this);
        // framework
        QdailyCodeApp.onCreate(this, isDebugMode);

        // init config
        QDConfigManager.getInstance().initConfig(this);

        //check activity status
        registerActivityLifecycleCallbacks(new QDActivityLifecycleCallbacks());

        QDArticleWebViewFileCacheMgr.getInstance().init(this, new QDArticleWebViewFileCacheMgr.DownCompleteHandler());
        LoadingImageCache.getInstance().init(this);
//        CrashHandler.getInstance().init(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(isDebugMode);
        }

        if (isDebugMode)
        {
            QDTestServerSetHelper.getInstance().init(this);
        }
    }

}
